from WindowTotal import Brider
import tkinter as tk
import tkinter.messagebox as tms
import multiprocessing
from tkinter import ttk
import threading
import time

from windows import WidgetConfig
from windows.RadioBtn import CheckGroup, Box, RadioGroup
from Util.WorryManager import WorryManager


class WindowsExam:
    """

    DESCRIPTION
        考试界面

    """

    def __init__(self, FatherWindows=None, QueList=(), User=None, Time=None):
        """
        @desc 显示考试界面
        @param FatherWindows: 父窗口
        @param QueList:
        """

        # -------- 逻辑变量
        self.index = 0
        self.User = User
        self.Time = Time
        self.WorryManager = WorryManager(self.User)

        if QueList is None:
            QueList = [None]

        self.userKey = []

        self.ExamWindows = tk.Tk()

        self.FatherWindows, self.QueList = FatherWindows, QueList

        self._width, self._height = self.ExamWindows.winfo_screenwidth(), \
                                    self.ExamWindows.winfo_screenheight()
        # region 设置
        if self._width < 500 and self._height < 600:
            tms.showerror("错误", "分辨率不足 ~")
            return

        self.win_height, self.win_width = self.ExamWindows.winfo_height(), self.ExamWindows.winfo_width()

        self.ExamWindows.geometry(f"{self._width}x{self._height}+0+0")
        # tms.showinfo("开始考试", f"练习开始了哟 ~")

        # self.ExamWindows.geometry(f"1000x1000+0+0")

        self.ExamWindows.overrideredirect(True)
        # self.ExamWindows.bind("<Button-1>", lambda e: self.ExamWindows.quit())
        self.ExamWindows.wm_attributes("-topmost", 1)

        self.BasicBackColor = '#2B2B2B'
        self.BasicBlockColor = '#363B40'
        # endregion

        tk.Label(self.ExamWindows, bg=self.BasicBackColor).place(relx=0, rely=0, relwidth=1, relheight=1)

        self.TimeShow = tk.Label(self.ExamWindows, text="剩下\n nan \n秒", bg=self.BasicBlockColor, fg='white',
                                 font=WidgetConfig.util.Font(self.ExamWindows).Title)
        self.TimeShow.place(x=self._width - 200, width=200, y=0, height=200)

        self.userKey = [None for i in self.QueList]
        if Time:
            self.bkp = False
            self.t1 = threading.Thread(target=Event.ProcessTime, args=(self, self.Time, self.bkp))
            self.t1.daemon = True
            self.t1.start()

        self.UI_SET()
        self.setQue(0)

        self.ExamWindows.mainloop()

    def UI_SET(self, QueType: object = RadioGroup):
        """
        @desc ui_set 设置
        @param QueType 题型
        @return:
        """

        self.QueDisplay = WidgetConfig.WidgetConfig(
            self.BasicBlockColor,  # 背景颜色 默认粉色
            tk.Label(self.ExamWindows, fg="white", anchor=tk.NW,
                     justify='left'),  # 控件
            "　显然，ip地址粘在一起了，如果我们要每读取一次ip就换行一次，那只需要加入语句：t.insert(tk.INSERT, '\n')即可",
            # 文本内容
            WidgetConfig.util.Font(self.ExamWindows).H2_En  # 字体
        )
        self.QueDisplay.initFont()
        self.QueDisplayLabel = self.QueDisplay.getWidget()

        self.QueDisplayLabel.place(relx=0.25, y=20, relwidth=.5, relheight=.25)
        self.QueDisplayLabel['wraplength'] = self._width / 2

        self.Group = QueType()  # 复选按钮组 （RadioGroup就是单选按钮组）

        self.A = Box('red', 'white', "Option A", "green", "white", self.Group, "A", self.ExamWindows, "xx", False,
                     font="Big")
        self.B = Box('red', 'white', "Option A", "green", "white", self.Group, "B", self.ExamWindows, "xx", False,
                     font="Big")
        self.C = Box('red', 'white', "Option A", "green", "white", self.Group, "C", self.ExamWindows, "xx", False,
                     font="Big")
        self.D = Box('red', 'white', "Option A", "green", "white", self.Group, "D", self.ExamWindows, "xx", False,
                     font="Big")

        self.A_Label = self.A.getLabel()
        self.A_Label.place(relx=.25, rely=.35, relwidth=.5, relheight=.105)
        self.B_Label = self.B.getLabel()
        self.B_Label.place(relx=.25, rely=.5, relwidth=.5, relheight=.105)
        self.C_Label = self.C.getLabel()
        self.C_Label.place(relx=.25, rely=.65, relwidth=.5, relheight=.105)
        self.D_Label = self.D.getLabel()
        self.D_Label.place(relx=.25, rely=.8, relwidth=.5, relheight=.105)
        self.D_Label['wraplength'] = self._width / 2
        self.C_Label['wraplength'] = self._width / 2
        self.B_Label['wraplength'] = self._width / 2
        self.A_Label['wraplength'] = self._width / 2
        self.side_nav = tk.Listbox(self.ExamWindows)
        self.side_nav['font'] = WidgetConfig.util.Font(self.ExamWindows).Text_2
        # self.side_nav.insert("end", f'使用滑轮滑动')
        for item in range(len(self.QueList)):
            self.side_nav.insert("end", f'第 {item + 1} 题')

        self.side_nav.place(relx=0, relheight=1, relwidth=.05)

        self.lastButton = tk.Label(self.ExamWindows, text="上一题", bg=self.BasicBlockColor, fg="white",
                                   font=WidgetConfig.util.Font(self.ExamWindows).Text_2)
        self.lastButton.place(x=self._width - 200, width=200, rely=.3, height=120)

        self.nextButton = tk.Label(self.ExamWindows, text="下一题", bg=self.BasicBlockColor,
                                   fg="white", font=WidgetConfig.util.Font(self.ExamWindows).Text_2)
        self.nextButton.place(x=self._width - 200, width=200, rely=.5, height=120)

        self.Over = tk.Label(self.ExamWindows, text="交卷", bg=self.BasicBlockColor,
                             fg="white", font=WidgetConfig.util.Font(self.ExamWindows).Text_2)
        self.Over.place(y=self._height - 200, height=200, x=self._width - 200,
                        width=200)
        self.Over.bind("<Button-1>", lambda e: self.Commit())
        n, l = self.index + 1, self.index - 1
        l = 0 if l < 0 else l
        n = 0 if n < 0 else n
        l = len(self.QueList) - 1 if l > len(self.QueList) else l
        n = len(self.QueList) + 1 if n > len(self.QueList) else n
        self.nextButton.bind("<Button-1>", lambda e: self.setQue(n))
        self.lastButton.bind("<Button-1>", lambda e: self.setQue(l))
        self.side_nav.bind("<Double-Button-1>", lambda e: Event.SideClicked(self, self.side_nav))

    def Commit(self, closeThread=True):
        """
        交卷
        @return:
        """
        if closeThread:
            self.bkp = True
        self.getUserSelect()
        self.statisticsWorry()
        self.ExamWindows.destroy()

        self.TextWorry = tk.Text(self.FatherWindows)
        self.TextWorry.place(relwidth=.8, relx=.1, y=130, relheight=.7)
        value = Brider.Brider.Apdate(Brider.Brider.readTemp())
        self.TextWorry.insert("insert", "工具提示 F1 字体缩小 F2 字体放大\r\n\r\n\r\n    ")

        self.TextWorry.insert("insert", value)
        self.TextWorry.insert("insert", "\r\n以上均为本次错题 None代表未填写")
        self.Value = 12

        def a(e=...):
            self.Value += 1
            self.TextWorry['font'] = ('微软雅黑', self.Value)

        def b(e=...):
            self.Value -= 1
            self.TextWorry['font'] = ('微软雅黑', self.Value)

        self.FatherWindows.bind("<F1>", b)
        self.FatherWindows.bind("<F2>", a)
        a()
    def statisticsWorry(self):
        """
        错题统计
        @return:
        """
        Worry = []
        trueKey = [i[-1] for i in self.QueList]
        small_index = 0
        temp = ...
        for userKey_item, trueKey_item in zip(self.userKey, trueKey):
            if userKey_item != trueKey_item:
                temp = self.QueList[small_index] + [self.userKey[small_index]]
                print(temp)
                Worry.append(temp)
                if not temp in self.WorryManager.read():
                    self.WorryManager.WriteWorry([temp])

            small_index += 1
        Brider.Brider.writeTemp(Worry) # 记录临时错误
        Brider.Brider.writeUser(Worry, self.User) # 记录错误到用户的错误集里

    def getUserSelect(self):
        """
        用户选择数据记录
        @return:
        """

        getValue = self.Group.GetActiveId()
        if isinstance(getValue, list):
            tmp = ''
            for i in getValue:
                tmp += i
            getValue = tmp
        self.indexApdate()
        self.userKey[self.index] = getValue

    def indexApdate(self):
        """
        自动修复index
        @return:
        """
        if self.index < 0:
            self.index = 0
        if self.index >= len(self.QueList):
            self.index = len(self.QueList) - 1

    def setUserSelect(self):
        """
        回归用户的选择
        @return:
        """
        mapper = {
            'A': self.A,
            'B': self.B,
            'C': self.C,
            'D': self.D,
        }
        userKey = self.userKey[self.index]
        if userKey is not None:
            userKey = str(userKey)
            for i in userKey:
                mapper.get(i).Active(True)

    def setQue(self, index=None):
        """
        设置index道题的界面
        @param index:  第index道题 并将index给属性 如果没有就按照self.index设置
        @return:
        """

        self.getUserSelect()

        tmp = index
        if index or index == 0:
            self.index = index

        if self.index < 0 or self.index >= len(self.QueList):
            self.index = tmp
            return
        try:
            Key: str = str((self.QueList[self.index])[-1])
        except:
            # print(self.QueList[self.index])
            ...

        if len(Key) > 1:
            self.UI_SET(QueType=CheckGroup)
        else:
            self.UI_SET(QueType=RadioGroup)

        self.QueDisplayLabel['text'], self.A_Label['text'], self.B_Label['text'], self.C_Label['text'], self.D_Label[
            'text'], _ = self.QueList[self.index][0:6]
        self.indexApdate()
        # print(self.index)
        self.setUserSelect()


class Event:
    @staticmethod
    def SideClicked(Win, Side):
        selectedIndex = Side.curselection()[0]
        # print(selectedIndex)
        Win.setQue(selectedIndex)

    @staticmethod
    def ProcessTime(win: WindowsExam, sec, bkp):
        """
        时间进程
        @return:
        """
        while sec >= 0:
            win.TimeShow['text'] = f"剩下\n {sec} \n秒"
            if sec < 100:
                win.TimeShow['fg'] = 'red'
                win.TimeShow['text'] = f"仅剩下\n {sec} \n秒"

            sec -= 1
            time.sleep(1)

            if win.bkp:
                return
        # win.ExamWindows.geometry('0x0')
        tms.showwarning("提示", "考试时间结束")
        win.ExamWindows.destroy()
        win.Commit(False)


if __name__ == '__main__':
    WindowsExam('', [
        ["FirstQue:", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", 'B', 'C', 'D', "A"],
        ["SecondQue:", "A", 'B', 'C', 'D', "AB"],
        ["ThirdQue:", "A", 'B', 'C', 'D', "C"]
    ], 123, 110)
